//* Copyright(C) 2005-2014, all rights reserved.
//*
//* The following code is copyrighted and contains proprietary information
/* and trade secrets of Foxit Software Inc.      
 **************************************************************************
 */
define(function (require, exports, module) {
    require('../ViewLevel.js');
    var LayoutInfo = require('./LayoutInfo');
    var CommonTools = require('../Common');
    var Config = require("../Config");
    /**
     *
     * @param readerApp
     * @param docView
     * @param layoutInfo
     * @constructor
     * @ignore
     */
    SinglePageViewLayout = function (readerApp, docView, layoutInfo) {
        var _docView = docView;
        var _readerApp = readerApp;
        var _layoutInfo = layoutInfo,
            _self = this;
        if (WebPDF.Environment.mobile) {
            _layoutInfo.marginX = 3;
        }
        else {
            _layoutInfo.marginX = 15;
        }
        var _blankImg = "";

        function _calcLayoutFacingCount() {
            //目前只提供单页
            var facingCount = 1;
            var pageCount = _docView.getPageCount();
            if (_layoutInfo.isFacing) {
                facingCount = (_layoutInfo.facingCount <= pageCount) ? _layoutInfo.facingCount : pageCount;
            }
            return facingCount;
        }

        this.getFitPageScale = function() {
            var maxHeight = _docView.getMaxPageViewHeight();
            var maxWidth = _docView.getMaxPageViewWidth();
            return _getFitRectScale(maxWidth, maxHeight);
        }

        this.getFitWidthScale = function (bUserPDFWidth) {
            var nFacingCount = _calcLayoutFacingCount();
            var maxPageWidth = _docView.getMaxPageViewWidth(!bUserPDFWidth);
            return _calcFitWidthScale(_layoutInfo.marginX, maxPageWidth,
                _layoutInfo.pageSpace, nFacingCount);
        };

        function _calcFitWidthScale(marginX, pageWidth, nPageSpace_H, facingCount) {
            var scrollApi = _docView.getScrollApi();
            var scrollBarWidth = scrollApi.getScrollBarWidth();
            var a = _docView.getDocViewWidth() - scrollBarWidth - 2 * marginX - nPageSpace_H * (facingCount - 1);
            var scale = a / pageWidth;
            var realScrollBarWidth = _docView.getRealScrollBarWidth(scale);
            if (scrollBarWidth != realScrollBarWidth) {
            	a = a + scrollBarWidth - realScrollBarWidth;
                scale = a / pageWidth;
            }
            //scale = Math.round(scale * 100) / 100;
            return scale;
        }

        this.getFitHeightScale = function () {
           // var mh = _docView.GetMaxPageViewHeight();
           // return _calcFitHeightScale(_layoutInfo.cyMargin, mh);
            return 1;
        };

        function _getFitRectScale(rectWidth, rectHeight) {
            var facingCount = _calcLayoutFacingCount();
            return _calcFitRectangleScale(_layoutInfo.marginX,
                _layoutInfo.marginY,
                rectWidth, rectHeight,
                _layoutInfo.pageSpace,
                facingCount);
        }

        function _calcLayoutScale(zoomToMode, scale, fitRectHeight, fitRectWidth) {
            var newScale = scale;
            switch (zoomToMode) {
                case WebPDF.PDFView.RD_ZMODE_CUSTOM:
                    newScale = scale;
                    break;
                case WebPDF.PDFView.RD_ZMODE_ACTUAL_SIZE:
                    newScale = 1.0;
                    break;
                case WebPDF.PDFView.RD_ZMODE_FIT_PAGE:
                    newScale = _self.getFitPageScale();
                    break;
                case WebPDF.PDFView.RD_ZMODE_FIT_WIDTH:
                    newScale = _self.getFitWidthScale();
                    break;
                case WebPDF.PDFView.RD_ZMODE_FIT_HEIGHT:
                    newScale = _self.getFitHeightScale();
                    break;
                case WebPDF.PDFView.RD_ZMODE_FIT_RECTANGLE:
                    newScale = (fitRectWidth <= -1 && fitRectHeight <= -1) ? scale : _getFitRectScale(fitRectWidth, fitRectHeight);
                    break;
                case WebPDF.PDFView.RD_ZMODE_NONE:
                    break;
                default:
                    break;
            }

            newScale = _getLayoutAdjustScale(newScale);
            if (newScale == 0 || newScale == "NaN")
                newScale = scale;
            return newScale;
        }

        function _getLayoutAdjustScale(scale) {
            scale = parseInt((scale + 0.2) / 0.5) * 0.5;

            if (scale < (_layoutInfo.minScale))
                return _layoutInfo.minScale;
            if (scale > _layoutInfo.maxScale)
                return _layoutInfo.maxScale;
            return scale;
        }


        //[计算按给定大小来显示时的显示倍数]
        function _calcFitRectangleScale(marginX, marginY, rectWidth, rectHeight, nPageSpace_H, facingCount) {

            //[计算按横向大小来显示时的显示倍数]	;
            var a1 = _docView.getDocViewWidth() - 2 * marginX - nPageSpace_H * (facingCount - 1);
            var dbScale1 = a1 / rectWidth;

            //[计算竖按向大小来显示时的显示倍数];

            var a2 = _docView.getDocViewHeight() - 2 * marginY;
            var dbScale2 = a2 / rectHeight;
            //[拿一个最小的倍数来计算];
            return (dbScale1 < dbScale2) ? dbScale1 : dbScale2;
        }

        function _setLayoutZoomToMode(iZoomMode) {
            _layoutInfo.iZoomMode = iZoomMode;
        }

        function _updatePreview(scale) {
            _layoutInfo.dbScale = scale;
            _docView.onZoom(_layoutInfo.dbScale);
        }

        /**
         * create html for doc view.
         * @returns {string}  html string for doc view.
         */
        this.createDocViewHtml = function () {
            var html = "";
            switch (_layoutInfo.showMode) {
                case WebPDF.PDFView.RD_BRMODE_CONTINUOUS:
                {
                    //不支持弹性滚动的不设置viewer div高度
                   /* if(WebPDF.Environment.mobile && _readerApp.getOptions().autoDetectElasticScroll && !$.support.isElasticScrollSupported){
                        html = "<div id='" + _docView.getDocViewContainerID() + "' class='fwr-pages scroll-pane' style='position:relative;width:"
                            + _docView.getDocViewWidth()  + "px; overflow-y: auto;overflow-x: auto;top:0px"
                            + "'></div>";
                    }
                    else {*/
                        html = "<div id='" + _docView.getDocViewContainerID() + "' class='fwr-pages scroll-pane' style='position:relative;width:"
                            + _docView.getDocViewWidth() + "px;height:" + _docView.getDocViewHeight() + "px; overflow-y: auto;overflow-x: auto;"
                            + "'></div>";
                    //}

                }break;
                case WebPDF.PDFView.RD_BRMODE_CONTINUOUS_FACING:
                {
                    html = "<div style='height:100%;" + "' class='scroll-pane'>" +
                        "<div id='" + _docView.getLeftDocContainerID() + "' class='' style='position:relative;top:0px;overflow:hidden;padding-top: 14px;float:left'></div><div id='" +
                        _docView.getRightDocContainerID() + "' class='' style='margin-left:10px;position:relative;top:0px;overflow:hidden;padding-top: 14px;float:left'></div></div>";
                }break;
                default:break;
            }
            return html;
        };

        
        

        /**
         * Create html for page view.
         * @param pageIndex Page index
         * @returns {String} Html for page view.
         */
        this.createPageViewHtml = function (pageIndex) {
            var pageView = _docView.getPageView(pageIndex);
            if (!pageView) {
                return "";
            }
            var scale = this.getScale();
            var pixelPerPoint = _readerApp.getPixelsPerPoint();
            var pageViewWidth = pageView.getPDFPageWidth() * scale * pixelPerPoint;
            var pageViewHeight = pageView.getPDFPageHeight() * scale * pixelPerPoint;
            pageView.setPageViewWidth(pageViewWidth);
            pageView.setPageViewHeight(pageViewHeight);
            var scrollApi = _docView.getScrollApi();
            var scrollBarWidth = scrollApi ? scrollApi.getScrollBarWidth() : 0 ;
            var leftMargin = (_docView.getDocViewWidth() - scrollBarWidth - pageViewWidth) / 2;
            var dimensions = "height:" + pageViewHeight + "px;width:" + pageViewWidth + "px;margin-left:" + leftMargin + "px;";
            var pageImgClass = "border  fwr-hidden fwr-page-bg-image";
            var loadingClass = "fwr-page-loading";
            var html = "";
            switch (_layoutInfo.showMode) {
                case WebPDF.PDFView.RD_BRMODE_CONTINUOUS:
                {
                    html = "<div class='fwr-page' id='" + pageView.getPageViewContainerID() + "' style='position:relative;" + dimensions + "'><div id='"
                        + pageView.getWrapPageID() + "' class='fwr-page border ' style='width:100%;height:100%' ></div><img alt='' src='" + _blankImg
                        + "' id='" + pageView.getPageBackgroundImgID() + "' class='" + pageImgClass + "' style='width:100%;height:100%;background-size:cover' />"
                        + "<div id='" + pageView.getPageLoaderImageID() + "' class='" +loadingClass+  "' />";
                    html += "</div>";
                }
                    break;
                case WebPDF.PDFView.RD_BRMODE_CONTINUOUS_FACING:
                {
                    html = "<div class='fwr-page' id='" + pageView.getPageViewContainerID() + "' style='position:relative;" + dimensions + "'><div id='"
                        + pageView.getWrapPageID() + "' class='fwr-page border ' style='width:100%;height:100%' ></div><img alt='' src='" + _blankImg
                        + "' id='" + pageView.getPageBackgroundImgID() + "' class='" + pageImgClass + "' style='width:100%;height:100%;background-size:cover' />"
                        + "<div id='" + pageView.getPageLoaderImageID() + "' class='" + loadingClass + "' />";
                    html += "</div>";
                }
                    break;
                default:
            }            
            return html;
        };

        /**
         * Use document fragment to insert html of pages to DOM.
         * @param startIndex Start page index
         * @param endIndex End page index
         * @param insertAfterPageIndex If this parameter set to -1, new html will be insert after last page which has been create.
         *      otherwise new html will be insert after this page.
         */
        this.createPagesView = function (startIndex, endIndex, pageIndexToInsert) {
            var pageViewInsertAfter = _docView.getPageView(pageIndexToInsert);
            var fragment = document.createDocumentFragment();
            for (var i = startIndex; i <= endIndex; i++) {
                var pageHtml = this.createPageViewHtml(i);
                var pageView = _docView.getPageView(i);
                pageView.render(pageHtml);             
                //_docView.$el.append(pageHtml);
                //_docView.$el.css({"width" : "100%"}).addClass("fwr-page-invisible");
                //ie8必须要有这层div，比较奇怪，如果不存在，有时候页面样式应用不成功
              //  var elem = document.createElement("div");
               // elem.innerHTML = pageHtml;
               // $(elem).css({"width" : "100%"}).addClass("fwr-page-invisible");             
                fragment.appendChild(pageView.el);                
                pageView.setContentCreatedState(true);
            }          
            if ( !pageViewInsertAfter){
               // console.log(_docView.$el.append)              
                _docView.$el.append(fragment);              
            }
              //  $("#" + _docView.getDocViewContainerID())[0].appendChild(fragment);
            else {
                pageViewInsertAfter.$el.after(fragment);
                //CommonTools.insertAfter(fragment, document.getElementById(insertPageID).parentNode);
            }
            return true;
        };

        /**
         * Get the page view offset relative to the document view.
         * @param pageIndex Page index
         * @returns {{x: number, y: number}}
         */
        this.getPageViewOffsetDocView = function (pageIndex) {
            var pageView = _docView.getPageView(pageIndex);
            if (!pageView.isContentCreated()) {
                return {x: 0, y: 0};
            }
            var pageOffset = pageView.$el.offset();
            var docViewOffset = _docView.$el.offset();
            return {x: docViewOffset.left - pageOffset.left, y: docViewOffset.top - pageOffset.top};
        };

        /**
         * Zoom and go to page.
         * @param zoomMode Zoom mode
         * @param scale Zoom level
         * @param fitRectWidth
         * @param fitRectHeight
         * @param isCalcScaleFromMode
         */
        this.zoomToPage = function (zoomMode, scale, fitRectWidth, fitRectHeight, isCalcScaleFromMode) {
            if (zoomMode <= WebPDF.PDFView.RD_ZMODE_CUSTOM || zoomMode > WebPDF.PDFView.RD_ZMODE_FIT_VISIBLE) {
                return;
            }
            if (zoomMode == 1) {
                scale = _getLayoutAdjustScale(scale);
            }
            //[改变缩放模式]
            _setLayoutZoomToMode(zoomMode);
            //[计算真正要缩放例]
            var newScale = _calcLayoutScale(zoomMode, scale, fitRectHeight,fitRectWidth, isCalcScaleFromMode);
            //[由比例更新Preview]

            _updatePreview(newScale);
        };

        /**
         * Get current scale.
         * @returns {Number} the scale.
         */
        this.getScale = function () {
            return _layoutInfo.scale;
        };
        /**
         * Set current scale.
         * @param scale
         */
        this.setScale = function (scale) {
            _layoutInfo.scale = scale;
        };
    };

    return module.exports = SinglePageViewLayout;
});